/*
 * DownloadMp3View.java
 */

package downloadmp3;

import downloadmp3.internals.Download;
import downloadmp3.internals.GlobalVars;
import downloadmp3.thread.Observador;
import java.awt.Label;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * The application's main frame.
 */
public class DownloadMp3View extends FrameView implements Runnable{

    public DownloadMp3View(SingleFrameApplication app) {
        super(app);

        initComponents();
       

        inicializarCampos();

        
        
        
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = 100;
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
        
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        
        

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                    
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }


                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    


                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    
                    
                    
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = DownloadMp3App.getApplication().getMainFrame();
            aboutBox = new DownloadMp3AboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        DownloadMp3App.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        campoEndereco = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        campoLocalEscolhido = new javax.swing.JTextField();
        boxAlterarLocalPadrao = new javax.swing.JCheckBox();
        botaoEscolherDiretorio = new javax.swing.JButton();
        botaoSair = new javax.swing.JButton();
        botaoDownload = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu menuArquivo = new javax.swing.JMenu();
        javax.swing.JMenuItem itemMenuSair = new javax.swing.JMenuItem();
        javax.swing.JMenu menuAjuda = new javax.swing.JMenu();
        javax.swing.JMenuItem sobreMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(downloadmp3.DownloadMp3App.class).getContext().getResourceMap(DownloadMp3View.class);
        campoEndereco.setText(resourceMap.getString("campoEndereco.text")); // NOI18N
        campoEndereco.setName("campoEndereco"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        campoLocalEscolhido.setText(resourceMap.getString("campoLocalEscolhido.text")); // NOI18N
        campoLocalEscolhido.setName("campoLocalEscolhido"); // NOI18N

        boxAlterarLocalPadrao.setText(resourceMap.getString("boxAlterarLocalPadrao.text")); // NOI18N
        boxAlterarLocalPadrao.setName("boxAlterarLocalPadrao"); // NOI18N
        boxAlterarLocalPadrao.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                boxAlterarLocalPadraoStateChanged(evt);
            }
        });
        boxAlterarLocalPadrao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boxAlterarLocalPadraoActionPerformed(evt);
            }
        });

        botaoEscolherDiretorio.setText(resourceMap.getString("botaoEscolherDiretorio.text")); // NOI18N
        botaoEscolherDiretorio.setName("botaoEscolherDiretorio"); // NOI18N
        botaoEscolherDiretorio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoEscolherDiretorioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(boxAlterarLocalPadrao))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(campoLocalEscolhido, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botaoEscolherDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(boxAlterarLocalPadrao)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(campoLocalEscolhido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botaoEscolherDiretorio))
                .addContainerGap(47, Short.MAX_VALUE))
        );

        botaoSair.setText(resourceMap.getString("botaoSair.text")); // NOI18N
        botaoSair.setName("botaoSair"); // NOI18N
        botaoSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoSairActionPerformed(evt);
            }
        });

        botaoDownload.setText(resourceMap.getString("botaoDownload.text")); // NOI18N
        botaoDownload.setName("botaoDownload"); // NOI18N
        botaoDownload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoDownloadActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(campoEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(228, 228, 228)
                        .addComponent(botaoDownload)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botaoSair)))
                .addContainerGap(43, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap(25, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(campoEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoDownload)
                    .addComponent(botaoSair))
                .addGap(21, 21, 21))
        );

        menuBar.setName("menuBar"); // NOI18N

        menuArquivo.setText(resourceMap.getString("menuArquivo.text")); // NOI18N
        menuArquivo.setName("menuArquivo"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(downloadmp3.DownloadMp3App.class).getContext().getActionMap(DownloadMp3View.class, this);
        itemMenuSair.setAction(actionMap.get("quit")); // NOI18N
        itemMenuSair.setText(resourceMap.getString("itemMenuSair.text")); // NOI18N
        itemMenuSair.setName("itemMenuSair"); // NOI18N
        menuArquivo.add(itemMenuSair);

        menuBar.add(menuArquivo);

        menuAjuda.setText(resourceMap.getString("menuAjuda.text")); // NOI18N
        menuAjuda.setName("menuAjuda"); // NOI18N

        sobreMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        sobreMenuItem.setText(resourceMap.getString("sobreMenuItem.text")); // NOI18N
        sobreMenuItem.setName("sobreMenuItem"); // NOI18N
        menuAjuda.add(sobreMenuItem);

        menuBar.add(menuAjuda);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addGap(138, 138, 138)
                .addComponent(jLabel3)
                .addContainerGap(142, Short.MAX_VALUE))
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addContainerGap())
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

private void botaoEscolherDiretorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoEscolherDiretorioActionPerformed
                JFileChooser fc = new JFileChooser();
                    
                // restringe a amostra a diretorios apenas
                fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                int res = fc.showOpenDialog(null);

                if(res == JFileChooser.APPROVE_OPTION){
                    File diretorio = fc.getSelectedFile();
                    this.campoLocalEscolhido.setText(diretorio.getAbsolutePath());
                }
            
}//GEN-LAST:event_botaoEscolherDiretorioActionPerformed

private void inicializarCampos(){
        this.campoEndereco.setText("");
        this.campoLocalEscolhido.setText(System.getProperty("user.home").toString());
        this.boxAlterarLocalPadrao.setSelected(true);
        this.campoLocalEscolhido.setEditable(false);
        this.botaoEscolherDiretorio.setEnabled(false);
        this.campoLocalEscolhido.setEnabled(false);
}

private void alterarCampos(boolean estado){
    this.campoEndereco.setEnabled(estado);
    this.campoLocalEscolhido.setEnabled(estado);
    this.botaoDownload.setEnabled(estado);
    this.botaoEscolherDiretorio.setEnabled(estado);
    this.boxAlterarLocalPadrao.setEnabled(estado);
    
}

private void ativarCampos(){
    alterarCampos(true);
}

private void desativarCampos(){
    alterarCampos(false);
}



private void botaoDownloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoDownloadActionPerformed
    if (this.validarCampos()){
        
        this.desativarCampos();
        //Observador obs = new Observador(this.label);
        //obs.start();
       
        this.start();
        
        Download.baixarArquivo(this.campoEndereco.getText(), this.campoLocalEscolhido.getText());
        
    }else{
        JOptionPane.showMessageDialog(null, "Preencha os campos correntamente.");
    }
}//GEN-LAST:event_botaoDownloadActionPerformed

private void botaoSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoSairActionPerformed
    System.exit(0);
}//GEN-LAST:event_botaoSairActionPerformed

private void boxAlterarLocalPadraoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_boxAlterarLocalPadraoStateChanged
    
}//GEN-LAST:event_boxAlterarLocalPadraoStateChanged

private void boxAlterarLocalPadraoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boxAlterarLocalPadraoActionPerformed
    //JOptionPane.showMessageDialog(null, "Estado alterado");
    alterarEstadoCampos();
    
}//GEN-LAST:event_boxAlterarLocalPadraoActionPerformed

private void alterarEstadoCampos(){
  if (this.boxAlterarLocalPadrao.isSelected()){
        this.campoLocalEscolhido.setText(System.getProperty("user.home").toString());
        //this.boxAlterarLocalPadrao.setSelected(true);
        this.campoLocalEscolhido.setEditable(false);
        this.botaoEscolherDiretorio.setEnabled(false);
        this.campoLocalEscolhido.setEnabled(false);
  }else{
        this.campoLocalEscolhido.setText("");
        //this.boxAlterarLocalPadrao.setSelected(true);
        this.campoLocalEscolhido.setEditable(true);
        this.botaoEscolherDiretorio.setEnabled(true);
        this.campoLocalEscolhido.setEnabled(true);
  }
    
}

private boolean validarCampos(){
    String endereco = this.campoEndereco.getText();
    String diretorio = this.campoLocalEscolhido.getText();
    
    if (endereco!=null && !endereco.equals("")&&diretorio!=null && !diretorio.equals("")){
        return true;
    }else{
        return false;
    }
    
}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoDownload;
    private javax.swing.JButton botaoEscolherDiretorio;
    private javax.swing.JButton botaoSair;
    private javax.swing.JCheckBox boxAlterarLocalPadrao;
    private javax.swing.JTextField campoEndereco;
    private javax.swing.JTextField campoLocalEscolhido;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables

    
    private ImageIcon imagem;
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private Thread th;
    
    private JDialog aboutBox;

    public void run() {
        Thread myThread = Thread.currentThread();
        while (th == myThread) {
            System.out.println("Itr--- --- --- --- ---");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e){
            // the VM doesn't want us to sleep anymore,
            // so get back to work
            }
            
            if (GlobalVars.isDownloadFinished()){
                System.out.println("terminou");
                JOptionPane.showMessageDialog(null, "Download Completo", "Download Completo", JOptionPane.INFORMATION_MESSAGE);
                this.ativarCampos();
                th = null;
                
            }
        }
    }

    
    public void start() {
        if (th == null) {
            th = new Thread(this, "Clock");
            th.start();
        }
    }

    public void stop() {
        th = null;
    }

}
